import React, { useState, useCallback } from 'react';
import { 
  Modal, Form, Input, Radio, Button, Space, Tooltip, Upload, message, Card, Avatar
} from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import http from '../api/http';
import { apiBaseURL, imgBaseURL } from '../api/baseURL';
import type { UploadProps } from 'antd';
import type { IImage } from '~/types/system';



// 表单值类型定义
interface OrderFormValues {
  id: number;
  name: string;
  code: string;
  helpCode: string;
  sex: '男' | '女' | '通用';
  maxage: number;
  minage: number;
  price: number;
  attention: string;
  img?: string;
  remark:string
}

interface Props {
  visible: boolean;
  gx:()=>void
}

const AddKK: React.FC<Props> = ({ visible,gx }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm<OrderFormValues>();
  const [avatarUrl, setAvatarUrl] = useState<string>(''); // 图片地址（对应img字段）
  const [uploading, setUploading] = useState<boolean>(false);

  // 打开弹窗（设置默认值）
  const showModal = () => {
    setIsModalOpen(true);
    form.setFieldsValue({
      id: 0,
      sex: '通用',
      minage: 18,
      maxage: 60,
      price:0

    });
    // 确保打开弹窗时图片为空
    setAvatarUrl('');
  };

  // 关闭弹窗：清空表单和图片
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields(); // 清空表单
    setAvatarUrl(''); // 清空图片
  };

  // 表单提交逻辑：提交后清空所有内容
  const handleFinish = async (values: OrderFormValues) => {
    try {
      // 构造提交数据（包含图片地址）
      const formData = { ...values, img: avatarUrl };
      console.log('提交数据:', formData);
      formData.maxage=parseInt(formData.maxage.toString())
       formData.minage=parseInt(formData.minage.toString())
       http.post("Setmeal",formData).then(res=>{

        if(res.code=="1"){
          message.success(res.msg)
          gx()
        }else{
         message.error(res.msg)
          
        }
       })
    
      form.resetFields(); // 清空所有表单字段
      setAvatarUrl(''); // 清空图片地址
      setIsModalOpen(false); // 关闭弹窗
    } catch (error) {
      message.error('提交失败，请重试');
    
    }
  };

  // 图片上传处理
  const handleAvatarChange: UploadProps['onChange'] = (info) => {
    setUploading(info.file.status === 'uploading');
    if (info.file.status === 'done') {
      const response = info.file.response.data as IImage;
      if (response) {
        setAvatarUrl(response.path);
        message.success('图片上传成功');
      } else {
        message.error('图片上传失败');
      }
    } else if (info.file.status === 'error') {
      message.error('图片上传失败，请重试');
    }
    if (info.file.status === 'done' || info.file.status === 'error') {
      setUploading(false);
    }
  };

  // 移除图片
  const handleRemoveAvatar = useCallback(() => {
    setAvatarUrl('');
  }, []);

  const uploadProps: UploadProps = {
    action: apiBaseURL + 'Upload',
    headers: { authorization: 'Bearer token' },
    onChange: handleAvatarChange,
    showUploadList: false,
    listType: 'picture',
    disabled: uploading,
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        套餐新增
      </Button>

      <Modal
        title="添加套餐信息"
        open={isModalOpen}
        onCancel={handleCancel}
        footer={[
          <Space key="footer" style={{ width: '100%', justifyContent: 'center' }}>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" onClick={() => form.submit()}>确认提交</Button>
          </Space>
        ]}
        width={600}
        centered
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFinish}
          initialValues={{ 
            id: 0, 
            sex: '通用', 
            minage: 0,
            maxage: 120 
          }}
        >
          <div style={{ display: 'flex', gap: 24 }}>
            <div style={{ flex: 1 }}>
              <Form.Item hidden
                name="id"
                label="套餐编号"
                rules={[{ required: true, message: '请输入套餐编号' }]}
              >
                <Input  placeholder="请输入套餐编号" />
              </Form.Item>
              <Form.Item 
                name="code"
                label="套餐编码"
                rules={[{ required: true, message: '请输入套餐编码' }]}
              >
                <Input  placeholder="请输入套餐编码" />
              </Form.Item>
              <Form.Item
                name="name"
                label="套餐名称"
                rules={[{ required: true, message: '请输入套餐名称' }]}
              >
                <Input placeholder="请输入套餐名称" />
              </Form.Item>

              <Form.Item
                name="helpCode"
                label="助记名"
                rules={[{ required: true, message: '请输入助记名' }]}
              >
                <Input placeholder="请输入助记名" />
              </Form.Item>

              <Form.Item
                name="sex"
                label="适用性别"
                rules={[{ required: true, message: '请选择性别' }]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value="男">男</Radio.Button>
                  <Radio.Button value="女">女</Radio.Button>
                  <Radio.Button value="通用">通用</Radio.Button>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="minage"
                label="最小年龄"
                rules={[
                  { required: true, message: '请输入最小年龄' },
                 
                ]}
              >
                <Input type="number" placeholder="请输入最小年龄" />
              </Form.Item>

              <Form.Item
                name="maxage"
                label="最大年龄"
                rules={[
                  { required: true, message: '请输入最大年龄' },
                 
                ]}
              >
                <Input type="number" placeholder="请输入最大年龄" />
              </Form.Item>

              <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格' }]}
              >
                <Input readOnly type="number" placeholder="请输入价格" />
              </Form.Item>

              <Form.Item
                name="attention"
                label="注意事项"
                rules={[{ required: true, message: '请输入注意事项' }]}
              >
                <Input placeholder="请输入注意事项" />
              </Form.Item>
             <Form.Item
                name="remark"
                label="描述"
                rules={[{ required: true, message: '请输入描述' }]}
              >
                <Input placeholder="请输入描述" />
              </Form.Item>
              <Form.Item
                name="img"
                label="图片"
                rules={[{ required: true, message: '请选择图片' }]}
              >
                <Upload {...uploadProps}>
                  <Card
                    hoverable
                    style={{
                      width: 160,
                      height: 160,
                      margin: '0 auto',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      border: '1px dashed #d9d9d9',
                      borderRadius: 8,
                      position: 'relative'
                    }}
                  >
                    {avatarUrl ? (
                      <>
                        <img
                          src={imgBaseURL+avatarUrl}
                          alt="套餐图片"
                          style={{
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                            borderRadius: 6
                          }}
                        />
                        <div style={{
                          position: 'absolute',
                          bottom: 0,
                          left: 0,
                          right: 0,
                          backgroundColor: 'rgba(0,0,0,0.5)',
                          color: 'white',
                          padding: '4px 0',
                          fontSize: 12,
                          borderRadius: '0 0 6px 6px',
                          display: 'flex',
                          justifyContent: 'space-around'
                        }}>
                          <span>点击更换</span>
                          <Tooltip title="移除图片">
                            <DeleteOutlined
                              onClick={(e) => {
                                e.stopPropagation();
                                handleRemoveAvatar();
                              }}
                              style={{ cursor: 'pointer' }}
                            />
                          </Tooltip>
                        </div>
                      </>
                    ) : (
                      <div style={{ textAlign: 'center', color: '#666' }}>
                        <UploadOutlined style={{ fontSize: 28, marginBottom: 8 }} />
                        <div>点击上传图片</div>
                        <div style={{ fontSize: 12, marginTop: 4, color: '#999' }}>
                          支持JPG、PNG格式
                        </div>
                      </div>
                    )}
                    {uploading && (
                      <div style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        backgroundColor: 'rgba(255,255,255,0.7)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}>
                        <span>上传中...</span>
                      </div>
                    )}
                  </Card>
                </Upload>
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>
    </>
  );
};

export { AddKK };